from xlwt import Workbook,easyxf, XFStyle, Alignment
from personInfo import personIdInfo, unitIdInfo

def getCurDataPersonIds(lstResultPrint):
    curKeysList = []
    for item in lstResultPrint.keys():
        # print(item )
        tmpID = item[-4:]
        # print("---", tmpID, tmpID[0])
        # print(tmpID[0], type(tmpID[0]), curKeysList, '@@@@@@@@@@@@@')
        # print(tmpID[0] not in curKeysList)
        if tmpID[0] not in curKeysList:
            curKeysList.append(tmpID[0])
        # if len(item) == 4:
        #     if item[0] not in curKeysList:
        #         curKeysList.append(item[0])

    dictUnitKeysNums = {}
    # print(curKeysList)
    # dictUnitNameLst = {}
    curKeysList.sort()
    for i,j in zip(curKeysList, list(range(0,len(curKeysList)))):
        dictUnitKeysNums[i] = j
        # dictUnitNameLst[i] = unitIdInfo[i]

    # print(dictUnitNameLst)
    return dictUnitKeysNums
    # print(dictUnitKeysNums)

# def getSheetNumFromPersonId(item):
#     tmpkey1firstnum = int(item[0])    

#     if len(item) == 5:
#         flag_Sheetnums = 0        
#     elif tmpkey1firstnum == 1:
#         flag_Sheetnums = 1
#     elif tmpkey1firstnum == 2:
#         flag_Sheetnums = 2
#     elif tmpkey1firstnum == 3:
#         flag_Sheetnums = 3
#     elif tmpkey1firstnum == 4:
#         flag_Sheetnums = 4
#     elif tmpkey1firstnum == 9:
#         flag_Sheetnums = 5

#     return flag_Sheetnums

def exportCard(lstResultPrint):
    #删除编号不在已知编号列表中的数据
    lstIdPPPP = personIdInfo.keys()
    ikey1lst = [item for item in lstResultPrint.keys()]
    ikey1lst.sort()
    # print(len(ikey1lst))
    for item in ikey1lst:
        if item not in lstIdPPPP:
            lstResultPrint.pop(item)

    DICT_SHEETNUM = getCurDataPersonIds(lstResultPrint)
    # print(DICT_SHEETNUM)
    book = Workbook(encoding='ascii')
    book1 = Workbook(encoding='ascii')
        # 'pattern: pattern solid,  fore_colour white;'

    # dateFormat = XFStyle()
    # dateFormat.num_format_str = 'mm/dd'
    # # dateFormat.alignment = "center"
    # dateFormat.alignment.vert = Alignment.VERT_CENTER 
    # dateFormat.alignment.horz = Alignment.HORZ_CENTER

    # style = easyxf(
    #     'font: height 280, name 黑体;'
    #     'align: vertical center, horizontal center;'
    #     )
    style2 = easyxf('font: height 200, name 宋体; align: vertical center, horizontal center;')
    style21 = easyxf('align: vertical center, horizontal center;')
    style3 = easyxf('font: height 260, name 仿宋_GB2312, bold True; align: vertical center, horizontal left, wrap True;')

    # sheet1 = book.add_sheet('打卡详情表', cell_overwrite_ok=True)
    # sheet1.col(0).width = 15*256
    
    irow = 1
    icol = 1

    ikeyUnitName = [item for item in DICT_SHEETNUM.keys()]
    ikeyUnitName.sort()
    lstUnitName = []
    for item in ikeyUnitName:
        lstUnitName.append(unitIdInfo[item])

    # lstUnitName = ["理事会", "办公室", "组联科", "康复科", "宣文科", "文体中心"]
    # print(lstUnitName)
    totalClass = len(lstUnitName)
    lstrows = []
    lstSheets = []
    for i in range(totalClass):
        lstrows.append(1)
        tmpsheet = book.add_sheet(lstUnitName[i] + '-考勤', cell_overwrite_ok=True)
        tmpsheet.col(0).width = 15*256
        lstSheets.append(tmpsheet)

    # print(len(lstSheets))
    # lstrows = [1 for i in range(totalClass)]
    # lstSheets = [book.add_sheet(str(i) + '__打卡详情表', cell_overwrite_ok=True) for i in range(totalClass)]
    # [lstSheets[i].col(0).width = 15*256 for i in ragne(totalClass)]
    flag_Sheetnums = -1

    dateSumCards = {} #按日期求各种考勤情况和
   
    ikey1lst = [item for item in lstResultPrint.keys()]
    ikey1lst.sort()
    # print(len(ikey1lst))
    for ikey1 in ikey1lst:
        # print(ikey1, DICT_SHEETNUM)
        # flag_Sheetnums = getSheetNumFromPersonId(ikey1)
        if len(ikey1) == 5:
            flag_Sheetnums = 0
        else:
            if len(DICT_SHEETNUM) == 1:
                flag_Sheetnums = 0
            else:
                flag_Sheetnums = DICT_SHEETNUM[ikey1[0]]
        # print(lstrows, flag_Sheetnums)
        irow = lstrows[flag_Sheetnums]
        sheet00 = lstSheets[flag_Sheetnums]

        # print(personIdInfo[ikey1], end=":")
        sheet00.write(0, 0, "编号", style2)
        sheet00.write(0, 1, "姓名", style2)
        sheet00.write(irow, 0, ikey1[-4:], style2)
        sheet00.write(irow, 1, personIdInfo[ikey1][0], style2)
        icol += 1

        tmpdatelst = [item for item in lstResultPrint[ikey1].keys()] #按日期排序
        tmpdatelst.sort()
        # lengthMerge = len(tmpdatelst)
        for ikey2 in tmpdatelst:
            if ikey2 not in dateSumCards.keys():
                dateSumCards[ikey2] = [0, 0] #分开上下午计数

            sheet00.col(icol).width = 12*256
            # print(ikey2)
            sheet00.write(0, icol, str(ikey2)[5:])
            # sheet00.write(0, icol, ikey2, dateFormat)

            if lstResultPrint[ikey1][ikey2][0][:2] == ["*", "*"]:
                dateSumCards[ikey2][0] += 1   #全勤计数
                dateSumCards[ikey2][1] += 1   #全勤计数            
            if lstResultPrint[ikey1][ikey2][0][:2] == ["2", "*"]:
                dateSumCards[ikey2][1] += 1   #下午计数
            if lstResultPrint[ikey1][ikey2][0][:2] == ["*", "3"]:
                dateSumCards[ikey2][0] += 1   #上午计数
            #     tmpdisp = "[2,*]"   #上午缺勤

            if lstResultPrint[ikey1][ikey2][0][:2] == ["2", "3"]:
                tmpdisp = "1"   #全天缺勤
                # lstPersonException.append([ikey1, ikey2, "11"])
            # elif lstResultPrint[ikey1][ikey2][0][:2] == ["2", "*"]:
            #     tmpdisp = "[2,*]"   #上午缺勤
            # elif lstResultPrint[ikey1][ikey2][0][:2] == ["*", "3"]:
            #     tmpdisp = "[*,3]"   #下午缺勤
            else:
                # tmpdisp = "[" + lstResultPrint[ikey1][ikey2][0][0:2] + "]"

                tmpdisp = "[" + lstResultPrint[ikey1][ikey2][0][0] + "," + lstResultPrint[ikey1][ikey2][0][1] + "]"
                for item in lstResultPrint[ikey1][ikey2][1:]:
                    if item[1] != "0":
                        tmpdisp += " | " + item[0] + "(" + item[1] + ")"

            sheet00.write(irow, icol, tmpdisp, style21)
            icol += 1

        # irow += 1
        lstrows[flag_Sheetnums] += 1
        icol = 1

    # print("*"*20)

    dispInfoTxt = '''说明：[*,*]代表上下午均已打卡。*:已打卡, 1:本日无有效打卡记录, 2:上午无打卡, 3:下午无打卡, 4:迟到, 5:早退, 6:早异常(7:20:00前打卡), 7:晚异常(20:00:00后打卡)'''    
        # sheet00.write(irow+1, 0, dispInfoTxt)
    for i in range(totalClass):
        isheet = lstSheets[i]
        irow = lstrows[i]
        isheet.write_merge(irow+1, irow+2, 0, 10, dispInfoTxt, easyxf('font: bold on; align:wrap on, vert centre, horiz left'))

    sheet2 = book.add_sheet('日期统计表',cell_overwrite_ok=True)
    sheet2.col(0).width = 15*256
    sheet2.col(2).width = 15*256
    tmpdatelst = [item for item in dateSumCards.keys()] #按日期排序
    tmpdatelst.sort()
    
    sheet2.write(0, 0, "日期", style2)
    sheet2.write(0, 1, "午次", style2)
    sheet2.write(0, 2, "有效打卡计数", style2)
    irow = 1
    for idate in tmpdatelst:
        # print(idate, type(idate))
        # tmpdate = str(idate)
        # sheet2.write(irow, 0, idate, dateFormat)
        sheet2.write(irow, 0, str(idate)[5:])
        sheet2.write(irow, 1, "上午", style2)
        sheet2.write(irow, 2, dateSumCards[idate][0], style2)
        irow += 1
        sheet2.write(irow, 0, str(idate)[5:])
        # sheet2.write(irow, 0, idate, dateFormat)
        sheet2.write(irow, 1, "下午", style2)
        sheet2.write(irow, 2, dateSumCards[idate][1], style2)
        irow += 1


    ## 打印每人的未打卡情况
    lstPersonException = [] #人员异常情况
    lstPersonException2 = [] #人员异常情况
    # ikey1lst = [item for item in lstResultPrint.keys()]
    # ikey1lst.sort()
    for ikey1 in ikey1lst:
        tmpdatelst = [item for item in lstResultPrint[ikey1].keys()] #按日期排序
        tmpdatelst.sort()
        for ikey2 in tmpdatelst:
            if lstResultPrint[ikey1][ikey2][0][:2] == ["2", "3"]:
                lstPersonException.append([ikey1, ikey2, "全天未打"])
            else:
                if lstResultPrint[ikey1][ikey2][0][0] == "2":
                    lstPersonException.append([ikey1, ikey2, "上午未打"])
                if lstResultPrint[ikey1][ikey2][0][1] == "3":
                    lstPersonException.append([ikey1, ikey2, "下午未打"])
                if lstResultPrint[ikey1][ikey2][0][0] == "4":
                    # lstPersonException.append([ikey1, ikey2, "上午迟到"])
                    lstPersonException2.append([ikey1, ikey2, "上午迟到"])
                if lstResultPrint[ikey1][ikey2][0][1] == "5":
                    # lstPersonException.append([ikey1, ikey2, "下午早退"])
                    lstPersonException2.append([ikey1, ikey2, "下午早退"])

    # for item in lstPersonException:
    #     print(item[0], item[1], item[2])
    # 异常情况
    lstrows2 = []
    lstSheets2 = []
    for i in range(totalClass):
        lstrows2.append(1)
        tmpsheet = book1.add_sheet(lstUnitName[i] + '-异常', cell_overwrite_ok=True)
        tmpsheet.col(0).width = 15*256
        tmpsheet.col(2).width = 25*256
        tmpsheet.col(3).width = 25*256
        tmpsheet.col(4).width = 25*256
        tmpsheet.col(5).width = 25*256
        lstSheets2.append(tmpsheet)

    # tiaoshiMaxLength = 0
    for item in lstPersonException:
        # flag_Sheetnums = getSheetNumFromPersonId(item[0])   
        if len(item[0]) == 5:
            flag_Sheetnums = 0
        else:
            if len(DICT_SHEETNUM) == 1:
                flag_Sheetnums = 0
            else:
                flag_Sheetnums = DICT_SHEETNUM[item[0][0]]
            # flag_Sheetnums = DICT_SHEETNUM[item[0][0]]     

        # print(flag_Sheetnums)
        irow = lstrows2[flag_Sheetnums]
        sheet00 = lstSheets2[flag_Sheetnums]
        sheet00.write(0, 0, "编号", style2)
        sheet00.write(0, 1, "姓名", style2)
        sheet00.write(0, 2, "职务", style2)
        sheet00.write(0, 3, "无打卡日期", style2)
        sheet00.write(0, 4, "无打卡原因", style2)
        sheet00.write(0, 5, "领导签字", style2)
        sheet00.write(irow, 0, item[0][-4:], style2)
        sheet00.write(irow, 1, personIdInfo[item[0]][0], style2)
        tmpZhiwu = personIdInfo[item[0]][1]
        
        # sheet00.write(irow, 2, "长"*15)
        sheet00.write(irow, 2, tmpZhiwu)
        sheet00.write(irow, 3, str(item[1])+item[2], style2)
        sheet00.write(irow, 4, "", style2)
        sheet00.write(irow, 5, "", style2)

        lstrows2[flag_Sheetnums] += 1


    #======================缺勤/迟到/早退/=============
    lstrows3 = []
    lstSheets3 = []
    for i in range(totalClass):
        lstrows3.append(1)
        tmpsheet = book1.add_sheet(lstUnitName[i] + '-迟到|早退', cell_overwrite_ok=True)
        tmpsheet.col(0).width = 15*256
        tmpsheet.col(2).width = 25*256
        tmpsheet.col(3).width = 25*256
        tmpsheet.col(4).width = 25*256
        lstSheets3.append(tmpsheet)

    # tiaoshiMaxLength = 0
    for item in lstPersonException2:
        # flag_Sheetnums = getSheetNumFromPersonId(item[0])   
        if len(item[0]) == 5:
            flag_Sheetnums = 0
        else:
            if len(DICT_SHEETNUM) == 1:
                flag_Sheetnums = 0
            else:
                flag_Sheetnums = DICT_SHEETNUM[item[0][0]]
            # flag_Sheetnums = DICT_SHEETNUM[item[0][0]]     

        # print(flag_Sheetnums)
        irow = lstrows3[flag_Sheetnums]
        sheet00 = lstSheets3[flag_Sheetnums]
        sheet00.write(0, 0, "编号", style2)
        sheet00.write(0, 1, "姓名", style2)
        sheet00.write(0, 2, "职务", style2)
        sheet00.write(0, 3, "缺勤类型（迟到/早退、无故缺勤）", style2)
        sheet00.write(0, 4, "缺勤日期", style2)
        sheet00.write(irow, 0, item[0][-4:], style2)
        sheet00.write(irow, 1, personIdInfo[item[0]][0], style2)
        tmpZhiwu = personIdInfo[item[0]][1]
        
        # sheet00.write(irow, 2, "长"*15)
        sheet00.write(irow, 2, tmpZhiwu)
        sheet00.write(irow, 3, item[2], style2)
        sheet00.write(irow, 4, str(item[1]), style2)

        lstrows3[flag_Sheetnums] += 1

    # print(tiaoshiMaxLength, "====")

    try:
        book.save('d:/考勤201707.xls')
        book1.save('d:/考勤201707-异常.xls')
    except  Exception as e:
        print(e.errno, e.strerror)
    return

    # sheet1.write_merge(11,11,0,7,'………………………………………………………………………………………………………………', easyxf('font: height 240, name 宋体; align: vertical center, horizontal center;'))
    


if __name__ == "__main__":
    exportCard({"a":{"b":[[1,2], [3,4]]}})